import { ChunkExtractor } from "@loadable/server";
import { HelmetData } from "react-helmet";
import serialize from 'serialize-javascript';
import { minify } from "html-minifier";

export default (
    head: HelmetData,
    extractor: ChunkExtractor,
    htmlContent: string,
    initialState: typeof window.__INITIAL_STATE__,
): any => {
    const html = `
        <!doctype html>
            <html ${head.htmlAttributes.toString()}>
                <head>
                    <meta charset="utf-8" />
                    <meta name="viewport" content="width=device-width, initial-scale=1"/>
                    <meta name="theme-color" content="#000" />

                    <link rel="icon" href="/logo.png" />
                    <link rel="apple-touch-icon" href="/logo192.png" />
                    <link rel="mainfest" href="/mainfest.json" />

                    ${head.title.toString()}
                    ${head.base.toString()}
                    ${head.meta.toString()}
                    ${head.link.toString()}

                    ${extractor.getLinkTags()}
                    ${extractor.getStyleTags()}
                </head>
                <body>
                    <div id="react-view">${htmlContent}</div>
                    <script>
                        window.__INITIAL_STATE__ = ${serialize(initialState)}

                    </script>

                    ${extractor.getScriptTags()}
                    ${head.script.toString()}
                </body>
            <html>
    `;

    const minifyConfig = {
        collapseWhitespace: true,
        removeComments: true,
        trimCustomFragments: true,
        minifyCss: true,
        minifyJs: true,
        minifyURLs: true,
    }

    return __DEV__ ? html : minify(html, minifyConfig)

}